# 安装依赖：pip install pandas openpyxl tkinter tkcalendar
import tkinter as tk
from tkinter import messagebox, ttk, font
from tkcalendar import DateEntry  # 日期选择组件
import pandas as pd
from datetime import datetime
import json
import os

# ------------------- 界面美化配置 -------------------
class UITheme:
    """界面主题配置类 - 现代化设计"""
    # 主色调 - 更现代的配色方案
    PRIMARY_COLOR = "#2563EB"      # 现代蓝
    SECONDARY_COLOR = "#7C3AED"    # 紫色
    ACCENT_COLOR = "#F59E0B"       # 金黄色
    SUCCESS_COLOR = "#10B981"      # 翠绿色
    WARNING_COLOR = "#EF4444"      # 红色
    INFO_COLOR = "#06B6D4"         # 青色
    
    # 背景色 - 层次化设计
    BG_LIGHT = "#FFFFFF"          # 纯白
    BG_MEDIUM = "#F8FAFC"         # 超浅灰
    BG_DARK = "#1E293B"           # 深蓝灰
    BG_CARD = "#FFFFFF"           # 卡片背景
    
    # 文字色
    TEXT_DARK = "#0F172A"         # 深色文字
    TEXT_MEDIUM = "#64748B"       # 中等文字
    TEXT_LIGHT = "#FFFFFF"        # 浅色文字
    TEXT_MUTED = "#94A3B8"        # 静音文字
    
    # 边框色
    BORDER_COLOR = "#E2E8F0"      # 边框色
    BORDER_FOCUS = "#2563EB"      # 焦点边框
    
    # 阴影色（使用灰色替代透明效果）
    SHADOW_LIGHT = "#F1F5F9"     # 浅阴影
    SHADOW_MEDIUM = "#E2E8F0"    # 中阴影
    SHADOW_DARK = "#CBD5E1"      # 深阴影

class AdvancedUIEffects:
    """高级UI效果类 - 兼容打包版本"""
    
    @staticmethod
    def create_gradient_frame(parent, color1, color2, width=None, height=None):
        """创建渐变背景框架"""
        frame = tk.Frame(parent, bg=color1)
        if width and height:
            frame.configure(width=width, height=height)
        return frame
    
    @staticmethod
    def create_card_frame(parent, bg_color=None, padding=15, shadow=True):
        """创建卡片式框架"""
        if bg_color is None:
            bg_color = UITheme.BG_CARD
            
        # 外层阴影框架
        if shadow:
            shadow_frame = tk.Frame(parent, bg=UITheme.SHADOW_LIGHT, bd=0)
            card_frame = tk.Frame(shadow_frame, bg=bg_color, bd=1, relief="solid")
            card_frame.pack(padx=2, pady=2, fill=tk.BOTH, expand=True)
            return shadow_frame, card_frame
        else:
            card_frame = tk.Frame(parent, bg=bg_color, bd=1, relief="solid")
            return card_frame, card_frame
    
    @staticmethod
    def create_hover_button(parent, text, command, style_type="primary"):
        """创建带悬停效果的按钮"""
        colors = {
            "primary": (UITheme.PRIMARY_COLOR, "#1D4ED8"),
            "success": (UITheme.SUCCESS_COLOR, "#059669"),
            "warning": (UITheme.WARNING_COLOR, "#DC2626"),
            "info": (UITheme.INFO_COLOR, "#0891B2")
        }
        
        normal_color, hover_color = colors.get(style_type, colors["primary"])
        
        button = tk.Button(parent, text=text, command=command,
                          bg=normal_color, fg=UITheme.TEXT_LIGHT,
                          font=("Microsoft YaHei", 10, "bold"),
                          bd=0, padx=20, pady=10,
                          cursor="hand2", relief="flat")
        
        def on_enter(e):
            button.configure(bg=hover_color)
        
        def on_leave(e):
            button.configure(bg=normal_color)
        
        button.bind("<Enter>", on_enter)
        button.bind("<Leave>", on_leave)
        
        return button

def configure_styles():
    """配置TTK样式 - 现代化设计"""
    style = ttk.Style()
    
    # 配置主题
    style.theme_use('clam')
    
    # 配置标签框样式 - 现代卡片风格
    style.configure("Card.TLabelframe", 
                   background=UITheme.BG_CARD,
                   borderwidth=1,
                   relief="solid",
                   bordercolor=UITheme.BORDER_COLOR)
    style.configure("Card.TLabelframe.Label", 
                   background=UITheme.BG_CARD,
                   foreground=UITheme.PRIMARY_COLOR,
                   font=("Microsoft YaHei", 12, "bold"))
    
    # 配置按钮样式 - 现代扁平化
    style.configure("Modern.TButton",
                   background=UITheme.PRIMARY_COLOR,
                   foreground=UITheme.TEXT_LIGHT,
                   borderwidth=0,
                   font=("Microsoft YaHei", 10, "bold"),
                   padding=(20, 12),
                   relief="flat")
    style.map("Modern.TButton",
              background=[('active', "#1D4ED8"),
                         ('pressed', "#1E40AF")])
    
    style.configure("Success.TButton",
                   background=UITheme.SUCCESS_COLOR,
                   foreground=UITheme.TEXT_LIGHT,
                   borderwidth=0,
                   font=("Microsoft YaHei", 10, "bold"),
                   padding=(20, 12),
                   relief="flat")
    style.map("Success.TButton",
              background=[('active', "#059669"),
                         ('pressed', "#047857")])
    
    style.configure("Warning.TButton",
                   background=UITheme.WARNING_COLOR,
                   foreground=UITheme.TEXT_LIGHT,
                   borderwidth=0,
                   font=("Microsoft YaHei", 10, "bold"),
                   padding=(20, 12),
                   relief="flat")
    style.map("Warning.TButton",
              background=[('active', "#DC2626"),
                         ('pressed', "#B91C1C")])
    
    # 配置输入框样式 - 现代边框设计
    style.configure("Modern.TEntry",
                   borderwidth=2,
                   relief="solid",
                   bordercolor=UITheme.BORDER_COLOR,
                   fieldbackground=UITheme.BG_LIGHT,
                   foreground=UITheme.TEXT_DARK,
                   font=("Microsoft YaHei", 11),
                   padding=(12, 8))
    style.map("Modern.TEntry",
              bordercolor=[('focus', UITheme.BORDER_FOCUS)],
              lightcolor=[('focus', UITheme.BORDER_FOCUS)],
              darkcolor=[('focus', UITheme.BORDER_FOCUS)])
    
    # 配置表格样式 - 现代表格设计
    style.configure("Modern.Treeview",
                   background=UITheme.BG_LIGHT,
                   foreground=UITheme.TEXT_DARK,
                   rowheight=32,
                   borderwidth=1,
                   relief="solid")
    style.configure("Modern.Treeview.Heading",
                   background=UITheme.PRIMARY_COLOR,
                   foreground=UITheme.TEXT_LIGHT,
                   font=("Microsoft YaHei", 11, "bold"),
                   borderwidth=0,
                   relief="flat")
    style.map("Modern.Treeview",
              background=[('selected', UITheme.SECONDARY_COLOR)],
              foreground=[('selected', UITheme.TEXT_LIGHT)])
    
    # 配置标签样式
    style.configure("Title.TLabel",
                   background=UITheme.BG_CARD,
                   foreground=UITheme.TEXT_DARK,
                   font=("Microsoft YaHei", 11, "bold"))
    
    style.configure("Heading.TLabel",
                   background=UITheme.BG_CARD,
                   foreground=UITheme.PRIMARY_COLOR,
                   font=("Microsoft YaHei", 14, "bold"))

# ------------------- 全局变量 -------------------
data_list = []  # 存储录入的订单数据（不设置默认数据，所有数据都为录入数据）
DATA_FILE = "order_data.json"  # 数据文件路径
# Excel列顺序（与原始表格对齐）
COLUMNS = ["序号", "日期", "客户名称", "订单号", "订单金额", "已付金额", "未付金额"]

# ------------------- 数据存储函数 -------------------
def save_data():
    """保存数据到本地文件"""
    try:
        with open(DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(data_list, f, ensure_ascii=False, indent=4)
        update_status("✅ 数据已自动保存", "success")
    except Exception as e:
        messagebox.showerror("保存错误", f"数据保存失败：{str(e)}")
        update_status("❌ 数据保存失败", "error")

def load_data():
    """从本地文件加载数据"""
    global data_list
    try:
        if os.path.exists(DATA_FILE):
            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                loaded_data = json.load(f)
            
            # 检查数据格式并转换
            if isinstance(loaded_data, dict) and all(isinstance(key, str) and len(key.split('-')) == 3 for key in loaded_data.keys()):
                # 旧格式：以日期为键的字典，需要转换
                data_list = []
                for date_key, order_info in loaded_data.items():
                    # 转换旧格式到新格式
                    converted_order = {
                        "日期": date_key,
                        "客户名称": order_info.get("customer", "未知客户"),
                        "订单号": f"ORD{len(data_list) + 1:04d}",  # 生成订单号
                        "订单金额": float(order_info.get("amount", 0)),
                        "已付金额": float(order_info.get("amount", 0)) if order_info.get("status") == "已收款" else 0
                    }
                    data_list.append(converted_order)
                
                # 保存转换后的数据
                save_data()
                update_status(f"✅ 已转换并加载 {len(data_list)} 条记录", "success")
                
            elif isinstance(loaded_data, list):
                # 新格式：列表格式，直接使用
                data_list = loaded_data
                # 验证数据完整性
                for i, row in enumerate(data_list):
                    if not isinstance(row, dict):
                        continue
                    # 确保所有必要字段存在且为正确类型
                    if "订单金额" in row:
                        row["订单金额"] = float(row["订单金额"])
                    if "已付金额" in row:
                        row["已付金额"] = float(row["已付金额"])
                
                update_status(f"✅ 已加载 {len(data_list)} 条记录", "success")
            else:
                # 未知格式，重置
                data_list = []
                update_status("⚠️ 数据格式不识别，已重置", "warning")
        else:
            data_list = []
            update_status("📝 新建数据文件", "info")
    except Exception as e:
        messagebox.showerror("加载错误", f"数据加载失败：{str(e)}")
        data_list = []
        update_status("❌ 数据加载失败", "error")

# ------------------- 界面更新函数 -------------------
def refresh_table():
    """刷新数据表格显示"""
    # 清空现有数据
    for item in tree.get_children():
        tree.delete(item)
    
    # 重新插入数据
    for i, row in enumerate(data_list, 1):
        try:
            # 验证数据完整性
            if not isinstance(row, dict):
                continue
            
            # 确保必要字段存在
            required_fields = ["日期", "客户名称", "订单号", "订单金额", "已付金额"]
            if not all(field in row for field in required_fields):
                continue
            
            # 确保金额字段为数字类型
            order_amount = float(row["订单金额"]) if row["订单金额"] else 0
            paid_amount = float(row["已付金额"]) if row["已付金额"] else 0
            
            # 计算未付金额
            unpaid = order_amount - paid_amount
            
            # 格式化显示
            tree.insert("", "end", values=(
                i,
                row["日期"],
                row["客户名称"],
                row["订单号"],
                f"¥ {order_amount:,.0f}",
                f"¥ {paid_amount:,.0f}",
                f"¥ {unpaid:,.0f}"
            ))
        except (ValueError, TypeError, KeyError) as e:
            # 跳过有问题的数据行
            print(f"跳过有问题的数据行 {i}: {e}")
            continue
    
    # 更新统计
    update_statistics()

def update_statistics():
    """更新统计信息 - 简化版本（兼容打包）"""
    if not data_list:
        # 重置显示
        total_order_var.set("¥ 0")
        total_paid_var.set("¥ 0")
        total_unpaid_var.set("¥ 0")
        customer_listbox.delete(0, tk.END)
        return
    
    # 计算总计 - 增强数据验证
    try:
        total_order = 0
        total_paid = 0
        
        for row in data_list:
            if not isinstance(row, dict):
                continue
            
            try:
                order_amount = float(row.get("订单金额", 0))
                paid_amount = float(row.get("已付金额", 0))
                total_order += order_amount
                total_paid += paid_amount
            except (ValueError, TypeError):
                continue
        
        total_unpaid = total_order - total_paid
    except Exception as e:
        print(f"计算总计时出错: {e}")
        total_order = total_paid = total_unpaid = 0
    
    # 直接更新总计（移除动画以确保打包兼容性）
    total_order_var.set(f"¥ {total_order:,.0f}")
    total_paid_var.set(f"¥ {total_paid:,.0f}")
    total_unpaid_var.set(f"¥ {total_unpaid:,.0f}")
    
    # 客户统计 - 增强数据验证
    customer_stats = {}
    try:
        for row in data_list:
            if not isinstance(row, dict):
                continue
                
            customer = row.get("客户名称", "未知客户")
            if customer not in customer_stats:
                customer_stats[customer] = {"订单": 0, "已付": 0, "未付": 0}
            
            try:
                order_amount = float(row.get("订单金额", 0))
                paid_amount = float(row.get("已付金额", 0))
                
                customer_stats[customer]["订单"] += order_amount
                customer_stats[customer]["已付"] += paid_amount
                customer_stats[customer]["未付"] += (order_amount - paid_amount)
            except (ValueError, TypeError):
                continue
    except Exception as e:
        print(f"客户统计时出错: {e}")
        customer_stats = {}
    
    # 更新客户列表
    customer_listbox.delete(0, tk.END)
    for customer, stats in customer_stats.items():
        customer_listbox.insert(tk.END, f"👤 {customer}")
        customer_listbox.insert(tk.END, f"   📊 订单总额：¥ {stats['订单']:,.0f}")
        customer_listbox.insert(tk.END, f"   ✅ 已付总额：¥ {stats['已付']:,.0f}")
        customer_listbox.insert(tk.END, f"   ⏳ 未付总额：¥ {stats['未付']:,.0f}")
        customer_listbox.insert(tk.END, "")

def update_status(message, status_type="info"):
    """更新状态栏 - 简化版本"""
    colors = {
        "info": UITheme.INFO_COLOR,
        "success": UITheme.SUCCESS_COLOR,
        "warning": UITheme.WARNING_COLOR,
        "error": UITheme.WARNING_COLOR
    }
    
    status_label.configure(text=message, fg=colors.get(status_type, UITheme.TEXT_MEDIUM))
    
    # 简单的延时恢复（不使用threading）
    root.after(3000, lambda: status_label.configure(
        text="就绪 | 数据已自动保存到本地", 
        fg=UITheme.TEXT_LIGHT
    ))

# ------------------- 数据处理函数 -------------------
def validate_number_input(value, action):
    """验证数字输入"""
    if action == '1':  # 插入操作
        if value == '':
            return True
        try:
            float(value)
            return True
        except ValueError:
            return False
    return True

def submit_data():
    """提交订单数据 - 增强版本"""
    try:
        # 获取输入数据
        date_str = date_entry.get()
        customer_name = customer_entry.get().strip()
        order_no = order_no_entry.get().strip()
        order_amount = order_amt_entry.get().strip()
        paid_amount = paid_amt_entry.get().strip()
        
        # 验证数据
        if not all([customer_name, order_no, order_amount]):
            messagebox.showwarning("输入错误", "请填写客户名称、订单号和订单金额！")
            return
        
        try:
            order_amount = float(order_amount)
            paid_amount = float(paid_amount) if paid_amount else 0
        except ValueError:
            messagebox.showerror("输入错误", "金额必须是数字！")
            return
        
        if order_amount <= 0:
            messagebox.showerror("输入错误", "订单金额必须大于0！")
            return
        
        if paid_amount < 0:
            messagebox.showerror("输入错误", "已付金额不能为负数！")
            return
        
        if paid_amount > order_amount:
            messagebox.showerror("输入错误", "已付金额不能超过订单金额！")
            return
        
        # 添加数据
        new_data = {
            "日期": date_str,
            "客户名称": customer_name,
            "订单号": order_no,
            "订单金额": order_amount,
            "已付金额": paid_amount
        }
        
        data_list.append(new_data)
        
        # 保存数据
        save_data()
        
        # 清空输入框
        clear_inputs()
        
        # 刷新表格
        refresh_table()
        
        update_status("✅ 数据提交成功", "success")
        
    except Exception as e:
        messagebox.showerror("提交错误", f"数据提交失败：{str(e)}")
        update_status("❌ 数据提交失败", "error")

def clear_inputs():
    """清空输入框"""
    customer_entry.delete(0, tk.END)
    order_no_entry.delete(0, tk.END)
    order_amt_entry.delete(0, tk.END)
    paid_amt_entry.delete(0, tk.END)
    date_entry.set_date(datetime.now())

def delete_selected():
    """删除选中的记录"""
    selected_items = tree.selection()
    if not selected_items:
        messagebox.showwarning("选择错误", "请先选择要删除的记录！")
        return
    
    if messagebox.askyesno("确认删除", "确定要删除选中的记录吗？"):
        for item in selected_items:
            # 获取行号（从1开始）
            row_index = tree.index(item)
            # 删除数据
            if 0 <= row_index < len(data_list):
                del data_list[row_index]
        
        # 保存数据
        save_data()
        
        # 刷新表格
        refresh_table()
        
        update_status("✅ 记录删除成功", "success")

def edit_selected():
    """编辑选中的记录"""
    selected_items = tree.selection()
    if not selected_items:
        messagebox.showwarning("选择错误", "请先选择要编辑的记录！")
        return
    
    if len(selected_items) > 1:
        messagebox.showwarning("选择错误", "一次只能编辑一条记录！")
        return
    
    # 获取选中行的数据
    item = selected_items[0]
    row_index = tree.index(item)
    
    if 0 <= row_index < len(data_list):
        data = data_list[row_index]
        
        # 填充到输入框
        date_entry.set_date(datetime.strptime(data["日期"], "%Y/%m/%d"))
        customer_entry.delete(0, tk.END)
        customer_entry.insert(0, data["客户名称"])
        order_no_entry.delete(0, tk.END)
        order_no_entry.insert(0, data["订单号"])
        order_amt_entry.delete(0, tk.END)
        order_amt_entry.insert(0, str(data["订单金额"]))
        paid_amt_entry.delete(0, tk.END)
        paid_amt_entry.insert(0, str(data["已付金额"]))
        
        # 删除原记录
        del data_list[row_index]
        
        # 保存并刷新
        save_data()
        refresh_table()
        
        update_status("✏️ 记录已加载到输入框，请修改后提交", "info")

def on_tree_select(event):
    """表格选择事件"""
    pass

def export_excel():
    """导出数据到Excel（含汇总、客户统计和公式联动）"""
    if not data_list:
        messagebox.showwarning("导出错误", "没有数据可以导出！")
        return
    
    try:
        from openpyxl import Workbook
        from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
        from openpyxl.utils import get_column_letter
        import shutil
        
        # 固定的Excel文件名
        excel_filename = "应收账款统计表.xlsx"
        history_folder = "历史表格"
        
        # 如果Excel文件已存在，先备份到历史文件夹
        if os.path.exists(excel_filename):
            # 创建历史文件夹（如果不存在）
            if not os.path.exists(history_folder):
                os.makedirs(history_folder)
            
            # 生成历史文件名（带时间戳）
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            history_filename = f"应收账款统计表_{timestamp}.xlsx"
            history_path = os.path.join(history_folder, history_filename)
            
            # 移动现有文件到历史文件夹
            shutil.move(excel_filename, history_path)
            print(f"已将现有文件备份到: {history_path}")
        
        # 创建工作簿
        wb = Workbook()
        ws = wb.active
        ws.title = "应收账款统计表"
        
        # 准备数据
        data_for_export = []
        for i, row in enumerate(data_list, 1):
            data_for_export.append([
                i,
                row["日期"],
                row["客户名称"],
                row["订单号"],
                row["订单金额"],
                row["已付金额"]
            ])
        
        # 设置样式
        header_font = Font(name="Microsoft YaHei", size=12, bold=True, color="FFFFFF")
        header_fill = PatternFill(start_color="2563EB", end_color="2563EB", fill_type="solid")
        data_font = Font(name="Microsoft YaHei", size=10)
        border = Border(
            left=Side(style='thin'),
            right=Side(style='thin'),
            top=Side(style='thin'),
            bottom=Side(style='thin')
        )
        
        # 主数据区域 (A-G列)
        headers = ["序号", "日期", "客户名称", "订单号", "订单金额", "已付金额", "未付金额"]
        
        # 写入标题
        for col, header in enumerate(headers, 1):
            cell = ws.cell(row=1, column=col, value=header)
            cell.font = header_font
            cell.fill = header_fill
            cell.alignment = Alignment(horizontal="center", vertical="center")
            cell.border = border
        
        # 写入数据
        for row_idx, data_row in enumerate(data_for_export, 2):
            for col_idx, value in enumerate(data_row, 1):
                cell = ws.cell(row=row_idx, column=col_idx, value=value)
                cell.font = data_font
                cell.border = border
                if col_idx in [5, 6]:  # 金额列
                    cell.number_format = '¥#,##0'
                    cell.alignment = Alignment(horizontal="right")
        
        # 未付金额公式 (G列)
        for row_idx in range(2, len(data_for_export) + 2):
            cell = ws.cell(row=row_idx, column=7, value=f"=E{row_idx}-F{row_idx}")
            cell.font = data_font
            cell.number_format = '¥#,##0'
            cell.alignment = Alignment(horizontal="right")
            cell.border = border
        
        # 汇总统计区域 (I-J列)
        summary_row = 2
        ws.cell(row=summary_row, column=9, value="订单总额：").font = Font(name="Microsoft YaHei", size=11, bold=True)
        ws.cell(row=summary_row, column=10, value=f"=SUM(E2:E{len(data_for_export) + 1})").number_format = '¥#,##0'
        
        ws.cell(row=summary_row + 1, column=9, value="已付总额：").font = Font(name="Microsoft YaHei", size=11, bold=True)
        ws.cell(row=summary_row + 1, column=10, value=f"=SUM(F2:F{len(data_for_export) + 1})").number_format = '¥#,##0'
        
        ws.cell(row=summary_row + 2, column=9, value="未付总额：").font = Font(name="Microsoft YaHei", size=11, bold=True)
        ws.cell(row=summary_row + 2, column=10, value=f"=SUM(G2:G{len(data_for_export) + 1})").number_format = '¥#,##0'
        
        # 客户统计区域 (L-M列)
        customers = list(set(row["客户名称"] for row in data_list))
        customers.sort()
        
        customer_start_row = 2
        ws.cell(row=1, column=12, value="客户统计").font = header_font
        ws.cell(row=1, column=12).fill = header_fill
        
        current_row = customer_start_row
        for customer in customers:
            ws.cell(row=current_row, column=12, value=customer).font = Font(name="Microsoft YaHei", size=11, bold=True)
            
            # 使用SUMIF公式计算客户统计
            ws.cell(row=current_row + 1, column=12, value="订单总额：")
            ws.cell(row=current_row + 1, column=13, value=f'=SUMIF(C2:C{len(data_for_export) + 1},"{customer}",E2:E{len(data_for_export) + 1})').number_format = '¥#,##0'
            
            ws.cell(row=current_row + 2, column=12, value="已付总额：")
            ws.cell(row=current_row + 2, column=13, value=f'=SUMIF(C2:C{len(data_for_export) + 1},"{customer}",F2:F{len(data_for_export) + 1})').number_format = '¥#,##0'
            
            ws.cell(row=current_row + 3, column=12, value="未付总额：")
            ws.cell(row=current_row + 3, column=13, value=f'=SUMIF(C2:C{len(data_for_export) + 1},"{customer}",G2:G{len(data_for_export) + 1})').number_format = '¥#,##0'
            
            current_row += 5
        
        # 设置列宽
        column_widths = [8, 12, 15, 15, 15, 15, 15, 3, 12, 15, 3, 15, 15]
        for i, width in enumerate(column_widths, 1):
            ws.column_dimensions[get_column_letter(i)].width = width
        
        # 保存文件（覆盖现有文件）
        wb.save(excel_filename)
        
        # 成功消息
        backup_msg = ""
        if os.path.exists(history_folder):
            history_files = [f for f in os.listdir(history_folder) if f.endswith('.xlsx')]
            if history_files:
                backup_msg = f"\n\n📁 历史文件已保存到 '{history_folder}' 文件夹\n📄 历史文件数量: {len(history_files)} 个"
        
        messagebox.showinfo("导出成功", 
                           f"✅ 数据已导出到：{excel_filename}\n"
                           f"📊 文件大小：约 {os.path.getsize(excel_filename) / 1024:.1f} KB\n"
                           f"📈 数据行数：{len(data_list)} 条记录\n"
                           f"🔧 特色功能：\n"
                           f"  • 未付金额自动计算（公式联动）\n"
                           f"  • 汇总统计实时更新\n"
                           f"  • 客户统计自动分组{backup_msg}")
        
        update_status(f"✅ Excel已导出到 {excel_filename}，历史文件已备份", "success")
        
    except ImportError:
        messagebox.showerror("导出错误", "请先安装openpyxl库：pip install openpyxl")
        update_status("❌ 缺少依赖库", "error")
    except Exception as e:
        messagebox.showerror("导出错误", f"导出失败：{str(e)}")
        update_status("❌ 导出失败", "error")

# ------------------- 界面搭建 -------------------
root = tk.Tk()
root.title("📊 应收账款统计管理系统 - 稳定优化版")
root.geometry("1500x900")
root.configure(bg=UITheme.BG_MEDIUM)
try:
    root.state('zoomed')  # 最大化窗口
except:
    pass  # 如果不支持最大化，忽略错误

# 配置样式
configure_styles()

# 设置图标（如果有的话）
try:
    # root.iconbitmap("icon.ico")  # 如果有图标文件可以取消注释
    pass
except:
    pass

# 创建顶部标题栏 - 现代化设计
title_frame = AdvancedUIEffects.create_gradient_frame(root, UITheme.PRIMARY_COLOR, UITheme.SECONDARY_COLOR, height=80)
title_frame.pack(fill=tk.X)
title_frame.pack_propagate(False)

# 主标题
title_label = tk.Label(title_frame, 
                      text="📊 应收账款统计管理系统", 
                      bg=UITheme.PRIMARY_COLOR,
                      fg=UITheme.TEXT_LIGHT,
                      font=("Microsoft YaHei", 20, "bold"))
title_label.pack(expand=True, pady=(15, 5))

# 副标题
subtitle_label = tk.Label(title_frame, 
                         text="Professional Accounts Receivable Management System", 
                         bg=UITheme.PRIMARY_COLOR,
                         fg=UITheme.BG_MEDIUM,
                         font=("Arial", 11))
subtitle_label.pack(pady=(0, 15))

# 创建主框架 - 使用卡片式设计
main_container = tk.Frame(root, bg=UITheme.BG_MEDIUM)
main_container.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)

# 左侧输入区域 - 卡片设计
input_shadow, input_frame = AdvancedUIEffects.create_card_frame(main_container, UITheme.BG_CARD, shadow=True)
input_shadow.grid(row=0, column=0, sticky="nsew", padx=(0, 10))

# 输入区域标题
input_title = tk.Label(input_frame, text="📝 订单录入", 
                      bg=UITheme.BG_CARD, fg=UITheme.PRIMARY_COLOR,
                      font=("Microsoft YaHei", 14, "bold"))
input_title.pack(pady=(15, 20))

# 添加输入验证
vcmd = (root.register(validate_number_input), '%P', '%d')

# 输入组件容器
inputs_container = tk.Frame(input_frame, bg=UITheme.BG_CARD)
inputs_container.pack(fill=tk.BOTH, expand=True, padx=20, pady=(0, 20))

# 组件：日期
date_label = tk.Label(inputs_container, text="📅 日期", 
                     bg=UITheme.BG_CARD, fg=UITheme.TEXT_DARK,
                     font=("Microsoft YaHei", 11, "bold"))
date_entry = DateEntry(
    inputs_container, date_pattern="yyyy/mm/dd",
    background=UITheme.BG_LIGHT, 
    foreground=UITheme.TEXT_DARK, 
    borderwidth=2, 
    width=18,
    font=("Microsoft YaHei", 11)
)
date_entry.set_date(datetime.now())

# 组件：客户名称
customer_label = tk.Label(inputs_container, text="👤 客户名称", 
                         bg=UITheme.BG_CARD, fg=UITheme.TEXT_DARK,
                         font=("Microsoft YaHei", 11, "bold"))
customer_entry = ttk.Entry(inputs_container, width=25, font=("Microsoft YaHei", 11), style="Modern.TEntry")

# 组件：订单号
order_no_label = tk.Label(inputs_container, text="📋 订单号", 
                         bg=UITheme.BG_CARD, fg=UITheme.TEXT_DARK,
                         font=("Microsoft YaHei", 11, "bold"))
order_no_entry = ttk.Entry(inputs_container, width=25, font=("Microsoft YaHei", 11), style="Modern.TEntry")

# 组件：订单金额
order_amt_label = tk.Label(inputs_container, text="💰 订单金额", 
                          bg=UITheme.BG_CARD, fg=UITheme.TEXT_DARK,
                          font=("Microsoft YaHei", 11, "bold"))
order_amt_entry = ttk.Entry(inputs_container, width=25, font=("Microsoft YaHei", 11), 
                           style="Modern.TEntry", validate='key', validatecommand=vcmd)

# 组件：已付金额
paid_amt_label = tk.Label(inputs_container, text="✅ 已付金额", 
                         bg=UITheme.BG_CARD, fg=UITheme.TEXT_DARK,
                         font=("Microsoft YaHei", 11, "bold"))
paid_amt_entry = ttk.Entry(inputs_container, width=25, font=("Microsoft YaHei", 11), 
                          style="Modern.TEntry", validate='key', validatecommand=vcmd)

# 按钮框架
button_frame = tk.Frame(inputs_container, bg=UITheme.BG_CARD)

# 现代化按钮
submit_btn = AdvancedUIEffects.create_hover_button(button_frame, "✅ 提交数据", submit_data, "primary")
edit_btn = AdvancedUIEffects.create_hover_button(button_frame, "✏️ 编辑选中", edit_selected, "info")
delete_btn = AdvancedUIEffects.create_hover_button(button_frame, "🗑️ 删除选中", delete_selected, "warning")
clear_btn = AdvancedUIEffects.create_hover_button(button_frame, "🆕 清空输入", clear_inputs, "info")
export_btn = AdvancedUIEffects.create_hover_button(button_frame, "📊 导出Excel", export_excel, "success")

# 输入区域布局
date_label.grid(row=0, column=0, padx=10, pady=12, sticky="w")
date_entry.grid(row=0, column=1, padx=10, pady=12, sticky="ew")
customer_label.grid(row=1, column=0, padx=10, pady=12, sticky="w")
customer_entry.grid(row=1, column=1, padx=10, pady=12, sticky="ew")
order_no_label.grid(row=2, column=0, padx=10, pady=12, sticky="w")
order_no_entry.grid(row=2, column=1, padx=10, pady=12, sticky="ew")
order_amt_label.grid(row=3, column=0, padx=10, pady=12, sticky="w")
order_amt_entry.grid(row=3, column=1, padx=10, pady=12, sticky="ew")
paid_amt_label.grid(row=4, column=0, padx=10, pady=12, sticky="w")
paid_amt_entry.grid(row=4, column=1, padx=10, pady=12, sticky="ew")

# 按钮布局
button_frame.grid(row=5, column=0, columnspan=2, pady=20, sticky="ew")
submit_btn.pack(pady=4, fill=tk.X)
edit_btn.pack(pady=4, fill=tk.X)
delete_btn.pack(pady=4, fill=tk.X)
clear_btn.pack(pady=4, fill=tk.X)
export_btn.pack(pady=4, fill=tk.X)

# 配置输入区域的列权重
inputs_container.grid_columnconfigure(1, weight=1)

# 中间表格区域 - 卡片设计
table_shadow, table_frame = AdvancedUIEffects.create_card_frame(main_container, UITheme.BG_CARD, shadow=True)
table_shadow.grid(row=0, column=1, sticky="nsew", padx=10)

# 表格标题
table_title = tk.Label(table_frame, text="📈 应收账款统计表", 
                      bg=UITheme.BG_CARD, fg=UITheme.PRIMARY_COLOR,
                      font=("Microsoft YaHei", 14, "bold"))
table_title.pack(pady=(15, 20))

# 表格容器
table_container = tk.Frame(table_frame, bg=UITheme.BG_CARD)
table_container.pack(fill=tk.BOTH, expand=True, padx=20, pady=(0, 20))

# 创建Treeview表格
columns = ("序号", "日期", "客户名称", "订单号", "订单金额", "已付金额", "未付金额")
tree = ttk.Treeview(table_container, columns=columns, show="headings", height=20, style="Modern.Treeview")

# 设置列标题和宽度
tree.heading("序号", text="序号")
tree.heading("日期", text="日期")
tree.heading("客户名称", text="客户名称")
tree.heading("订单号", text="订单号")
tree.heading("订单金额", text="订单金额")
tree.heading("已付金额", text="已付金额")
tree.heading("未付金额", text="未付金额")

tree.column("序号", width=60, anchor=tk.CENTER)
tree.column("日期", width=110, anchor=tk.CENTER)
tree.column("客户名称", width=120, anchor=tk.CENTER)
tree.column("订单号", width=120, anchor=tk.CENTER)
tree.column("订单金额", width=130, anchor=tk.E)
tree.column("已付金额", width=130, anchor=tk.E)
tree.column("未付金额", width=130, anchor=tk.E)

# 绑定选择事件
tree.bind("<<TreeviewSelect>>", on_tree_select)

# 添加滚动条
scrollbar = ttk.Scrollbar(table_container, orient=tk.VERTICAL, command=tree.yview)
tree.configure(yscrollcommand=scrollbar.set)

# 表格布局
tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

# 右侧统计区域 - 卡片设计
stats_shadow, stats_frame = AdvancedUIEffects.create_card_frame(main_container, UITheme.BG_CARD, shadow=True)
stats_shadow.grid(row=0, column=2, sticky="nsew", padx=(10, 0))

# 统计区域标题
stats_title = tk.Label(stats_frame, text="📊 汇总统计", 
                      bg=UITheme.BG_CARD, fg=UITheme.PRIMARY_COLOR,
                      font=("Microsoft YaHei", 14, "bold"))
stats_title.pack(pady=(15, 20))

# 统计容器
stats_container = tk.Frame(stats_frame, bg=UITheme.BG_CARD)
stats_container.pack(fill=tk.BOTH, expand=True, padx=20, pady=(0, 20))

# 总计标签（使用现代卡片式布局）
# 订单总额卡片
order_card_shadow, order_card = AdvancedUIEffects.create_card_frame(stats_container, UITheme.PRIMARY_COLOR, shadow=True)
order_card_shadow.pack(fill=tk.X, pady=5)
total_order_var = tk.StringVar(value="¥ 0")
total_order_label = tk.Label(order_card, text="订单总额", 
                            bg=UITheme.PRIMARY_COLOR, 
                            fg=UITheme.TEXT_LIGHT,
                            font=("Microsoft YaHei", 10, "bold"))
total_order_label.pack(pady=(8, 2))
total_order_value = tk.Label(order_card, textvariable=total_order_var,
                            bg=UITheme.PRIMARY_COLOR, 
                            fg=UITheme.TEXT_LIGHT,
                            font=("Microsoft YaHei", 14, "bold"))
total_order_value.pack(pady=(2, 8))

# 已付总额卡片
paid_card_shadow, paid_card = AdvancedUIEffects.create_card_frame(stats_container, UITheme.SUCCESS_COLOR, shadow=True)
paid_card_shadow.pack(fill=tk.X, pady=5)
total_paid_var = tk.StringVar(value="¥ 0")
total_paid_label = tk.Label(paid_card, text="已付总额", 
                           bg=UITheme.SUCCESS_COLOR, 
                           fg=UITheme.TEXT_LIGHT,
                           font=("Microsoft YaHei", 10, "bold"))
total_paid_label.pack(pady=(8, 2))
total_paid_value = tk.Label(paid_card, textvariable=total_paid_var,
                           bg=UITheme.SUCCESS_COLOR, 
                           fg=UITheme.TEXT_LIGHT,
                           font=("Microsoft YaHei", 14, "bold"))
total_paid_value.pack(pady=(2, 8))

# 未付总额卡片
unpaid_card_shadow, unpaid_card = AdvancedUIEffects.create_card_frame(stats_container, UITheme.WARNING_COLOR, shadow=True)
unpaid_card_shadow.pack(fill=tk.X, pady=5)
total_unpaid_var = tk.StringVar(value="¥ 0")
total_unpaid_label = tk.Label(unpaid_card, text="未付总额", 
                             bg=UITheme.WARNING_COLOR, 
                             fg=UITheme.TEXT_LIGHT,
                             font=("Microsoft YaHei", 10, "bold"))
total_unpaid_label.pack(pady=(8, 2))
total_unpaid_value = tk.Label(unpaid_card, textvariable=total_unpaid_var,
                             bg=UITheme.WARNING_COLOR, 
                             fg=UITheme.TEXT_LIGHT,
                             font=("Microsoft YaHei", 14, "bold"))
total_unpaid_value.pack(pady=(2, 8))

# 客户统计区域
customer_frame_shadow, customer_frame_inner = AdvancedUIEffects.create_card_frame(stats_container, UITheme.BG_LIGHT, shadow=True)
customer_frame_shadow.pack(fill=tk.BOTH, expand=True, pady=(20, 0))

customer_frame_title = tk.Label(customer_frame_inner, text="👥 客户查询", 
                               bg=UITheme.BG_LIGHT, fg=UITheme.PRIMARY_COLOR,
                               font=("Microsoft YaHei", 12, "bold"))
customer_frame_title.pack(pady=(10, 5))

customer_listbox = tk.Listbox(customer_frame_inner, height=15, 
                             font=("Microsoft YaHei", 10),
                             bg=UITheme.BG_LIGHT,
                             fg=UITheme.TEXT_DARK,
                             selectbackground=UITheme.SECONDARY_COLOR,
                             selectforeground=UITheme.TEXT_LIGHT,
                             relief="flat",
                             bd=0)
customer_scrollbar = ttk.Scrollbar(customer_frame_inner, orient=tk.VERTICAL, command=customer_listbox.yview)
customer_listbox.configure(yscrollcommand=customer_scrollbar.set)

customer_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(10, 0), pady=(0, 10))
customer_scrollbar.pack(side=tk.RIGHT, fill=tk.Y, pady=(0, 10), padx=(0, 10))

# 配置网格权重
main_container.grid_columnconfigure(1, weight=2)  # 表格区域权重更大
main_container.grid_columnconfigure(0, weight=1)  # 输入区域
main_container.grid_columnconfigure(2, weight=1)  # 统计区域
main_container.grid_rowconfigure(0, weight=1)

# 状态栏 - 现代化设计
status_frame = tk.Frame(root, bg=UITheme.BG_DARK, height=30)
status_frame.pack(fill=tk.X, side=tk.BOTTOM)
status_frame.pack_propagate(False)

status_label = tk.Label(status_frame, 
                       text="就绪 | 数据已自动保存到本地", 
                       bg=UITheme.BG_DARK,
                       fg=UITheme.TEXT_LIGHT,
                       font=("Microsoft YaHei", 10))
status_label.pack(side=tk.LEFT, padx=15, pady=5)

# 版本信息
version_label = tk.Label(status_frame, 
                        text="v2.0 稳定优化版", 
                        bg=UITheme.BG_DARK,
                        fg=UITheme.TEXT_MUTED,
                        font=("Arial", 9))
version_label.pack(side=tk.RIGHT, padx=15, pady=5)

# 程序启动时加载数据
load_data()

# 初始化表格
refresh_table()

# 启动消息
update_status("🚀 系统启动成功，界面已优化（稳定版）", "success")

if __name__ == "__main__":
    root.mainloop()
